package com.glodon.paas.job.server.service;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.glodon.paas.job.model.MonitorEvent;
import com.glodon.paas.job.model.MonitorEventType;

@Service
public class ServerHeartBeat {

	private static final Logger	monitorLogger		= LoggerFactory.getLogger("monitor");
	private static final Logger	logger				= LoggerFactory.getLogger(ServerHeartBeat.class);

	private static final int	DEFAULT_HEART_BEAT	= 60000;
	private boolean				running				= true;

	@PostConstruct
	public void start() {
		Thread thread = new Thread() {
			@Override
			public void run() {
				while (running) {
					try {
						sendHeartBeat();
						Thread.sleep(DEFAULT_HEART_BEAT);
					} catch (Throwable e) {
						// ignores
						logger.warn("send heart beat failure", e.getMessage());
					}
				}
			}
		};
		thread.setDaemon(true);
		thread.start();
	}

	public void sendHeartBeat() throws UnknownHostException {
		MonitorEvent monitorEvent = new MonitorEvent();
		monitorEvent.setType(MonitorEventType.SERVER_STATUS);
		String address = InetAddress.getLocalHost().getHostAddress();
		monitorEvent.setTraceId(address);
		// monitorLogger.info("send heart beat", monitorEvent);
	}

	@PreDestroy
	public void stop() {
		running = false;
	}
}
